//
//  JZLoading.swift
//  Demo
//
//  Created by 久众科技 on 2018/9/5.
//  Copyright © 2018年 久众科技. All rights reserved.
//

import Foundation
import UIKit

class JZLoading: NSObject {
    
    enum LoadingType: Int, Codable {
        case normal  = 0
        case special = 1
    }
    
    static var LoadingView: UIView!
    static var imageView: UIImageView!
    //显示菊花
    static func showLoadingWith(toView: UIView, type: LoadingType? = .normal) {
        //先清除
        clearMaskView(toView: toView)
        //创建背景view
        let maskView = UIView(frame: (UIApplication.shared.keyWindow?.bounds)!)
        maskView.backgroundColor = UIColor(white: 0.3, alpha: 0.1)
        //赋值全局变量
        LoadingView = maskView
        //添加的桌面上
        UIApplication.shared.keyWindow?.addSubview(LoadingView)
        
        let size = type == .normal ? CGSize(width: 100, height: 100) : CGSize(width: 150, height: 80)
        
        let blackView = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        blackView.backgroundColor = UIColor(hexString: "#00000080")
        blackView.layer.cornerRadius = 10
        //放到正中间
        blackView.center = LoadingView.center
        LoadingView.addSubview(blackView)
        
        imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.frame = blackView.bounds
        
        if type == .special {
            imageView.frame = CGRect(x: 0, y: 0, width: 130, height: 60)
            imageView.center = CGPoint(x: blackView.width / 2, y: blackView.height / 2)
            blackView.backgroundColor = UIColor.white
        }
        
        if let type = type {
            let source = getImages(type)
            imageView.animationImages = source.images
            imageView.animationDuration = source.duration
            imageView.animationRepeatCount = type == .normal ? 300 : 1
            imageView.startAnimating()
            blackView.addSubview(imageView)
            
            if type == .special {
                DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 10.0) {
                    DispatchQueue.main.async{
                        imageView.image = source.images.last
                    }
                }
            }
        }
    }
    
    static func getImages(_ type: LoadingType) -> (images:[UIImage],duration:TimeInterval) {
        
        var images = [UIImage]()
        var duration: TimeInterval = 1.0
        if type == .normal {
            for i in 1...15 {
                images.append(UIImage(named: "\(i)")!)
            }
            return (images, 1.0)
        } else if type == .special {
            // 获取NSData类型
            guard let filePath = Bundle.main.path(forResource: "loading.gif", ofType: nil) else { return (images, duration) }
            guard let fileData = NSData(contentsOfFile: filePath) else { return (images, duration) }
            // 获取Data获取CGImageSource对象
            guard let imageSource = CGImageSourceCreateWithData(fileData, nil) else { return (images, duration) }
            // 获取GIF中图片的个数和时间
            let frameCount = CGImageSourceGetCount(imageSource)
            
            for i in 0 ..< frameCount {
                // 获取图片
                guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
                let image = UIImage(cgImage: cgImage)
                if 0 == i {
                    imageView.image = image
                }
                images.append(image)
                // 获取时长
                guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary] as? NSDictionary, let frameDuration = gifInfo[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
                duration += frameDuration.doubleValue
            }
            return (images, duration)
        }
        return (images, duration)
    }
    
    //判断有没有弹窗
    static func clearMaskView(toView: UIView) {
        LoadingView?.removeFromSuperview()
    }
    
    static func hideLoading() {
        LoadingView?.removeFromSuperview()
    }
}
